//
//  EditDynamicContentView.m
//  WeCommunity
//
//  Created by mac on 2017/6/16.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "EditDynamicContentView.h"
#import "ChoosePhotoView.h"
#import "PhotoAlbumModel.h"
#import "FullScreenImage.h"

#define MAX_TEXT_LENGTH 400

@interface EditDynamicContentView ()<UIGestureRecognizerDelegate,ChoosePhotoDelegate,LKeyBoardDelegate>
{
    CGFloat _imageWidth;
}
@property (nonatomic,strong) NSMutableArray * imageViewArray;
@property (nonatomic,strong) NSMutableArray * assstsArray;
@property (nonatomic,strong) UIImageView * addImageIcon;

@end

@implementation EditDynamicContentView

-(instancetype)initWithFrame:(CGRect)frame timeLineType:(NSInteger)timeLineType
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = WHITE_COLOR;
        self.timeLineType = timeLineType;
        
        [self addSubview:self.scrollView];
        [self.scrollView addSubview:self.textView];
        self.textView.inputAccessoryView = self.editToolView;
        [self.scrollView addSubview:self.addImageIcon];
        
        self.imageViewArray = [NSMutableArray array];
        _imageWidth = (KScreen_Width - 25) / 4;
        if (self.timeLineType == 0) {
            self.maxPhotoCount = 9;
        }else if (self.timeLineType == 1){
            self.maxPhotoCount = 1;
        }
        for (int i = 0; i < self.maxPhotoCount; i++) {
            ChoosePhotoView * photoView = [[ChoosePhotoView alloc] initWithFrame:CGRectMake(5 + (5 + _imageWidth) * (i % 4), CGRectGetMaxY(self.textView.frame) + 10 + (5 + _imageWidth) * (i / 4), _imageWidth, _imageWidth)];
            [photoView.chooseBtn setImage:[UIImage imageNamed:@"deletePhoto"] forState:UIControlStateNormal];
            photoView.delegate = self;
            photoView.hidden = YES;
            [self.scrollView addSubview:photoView];
            [self.imageViewArray addObject:photoView];
        }
    }
    return self;
}

#pragma mark -get
-(YYTextView *)textView
{
    if (!_textView) {
        _textView = [[YYTextView alloc] initWithFrame:CGRectMake(5, 5, KScreen_Width - 10,120)];
        _textView.showsVerticalScrollIndicator = NO;
        _textView.font = PFR_FONT(16);
        _textView.textColor = [UIColor blackColor];
        _textView.tintColor = TINT_GREEN_COLOR;
        _textView.delegate = self;
        _textView.clipsToBounds = YES;
        
        if (self.timeLineType == 0) {
            _textView.placeholderText = KNSLocal(@"editPlaceholder");
        }else if (self.timeLineType == 1){
            _textView.placeholderText = @"请输入发表的内容";
        }
        _textView.placeholderFont = PFL_FONT(16);
        _textView.placeholderTextColor =[UIColor colorWithHex:0x1d1d26 alpha:0.5];
        
    }
    return _textView;
}

-(UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KScreen_Width, CGRectGetHeight(self.bounds))];
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + 1);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
        tapGes.delegate = self;
        [_scrollView addGestureRecognizer:tapGes];
    }
    return _scrollView;
}
-(EditToolBarVIew *)editToolView
{
    if (!_editToolView) {
        _editToolView = [[EditToolBarVIew alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), 45) uiType:self.timeLineType];
        _editToolView.delegate = self;
    }
    return _editToolView;
}

-(UIImageView *)addImageIcon
{
    if (!_addImageIcon) {
        _addImageIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _imageWidth, _imageWidth)];
        [_addImageIcon setImage:[UIImage imageNamed:@"addPic"]];
        _addImageIcon.contentMode = UIViewContentModeScaleAspectFill;
        _addImageIcon.clipsToBounds = YES;
        _addImageIcon.exclusiveTouch = YES;
        _addImageIcon.userInteractionEnabled = YES;
        _addImageIcon.hidden = YES;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processAddPicicon)];
        [_addImageIcon addGestureRecognizer:tapGes];
    }
    return _addImageIcon;
}

-(void)processAddPicicon
{
    if (self.delegate) {
        //拍照
        [self.delegate editToolBarSeletedIndex:0];
    }
}

#pragma mark - 设置图片
-(void)loadAssetsArray:(NSMutableArray *)array
{
    self.assstsArray = array;
    for (int i = 0; i < self.imageViewArray.count; i++) {
        ChoosePhotoView * photoView = self.imageViewArray[i];
        if (i < array.count) {
            PhotoAlbumModel * model = array[i];
            photoView.hidden = NO;
            photoView.preViewPhotoAlbumModel = model;
        }else{
            photoView.hidden = YES;
        }
    }
    
    [self setAddPicIconStatus];
    
    [self setscrollViewContentSize];
    
}
#pragma mark - 设置界面滚动范围
-(void)setscrollViewContentSize
{
    if (self.assstsArray.count > 0) {
        ChoosePhotoView * photoView = self.imageViewArray[self.imageViewArray.count - 1];
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds), CGRectGetMaxY(photoView.frame) + 50);
    }else{
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + 1);
    }
}

#pragma mark -  设置添加照片的图标状态
-(void)setAddPicIconStatus
{
    NSInteger count = self.assstsArray.count;
    if (count < 1 || count >= self.maxPhotoCount) {
        self.addImageIcon.hidden = YES;
        return;
    }else{
        self.addImageIcon.hidden = NO;
    }
    [UIView animateWithDuration:0.15 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.addImageIcon.frame =  CGRectMake(5 + (5 + _imageWidth) * (count % 4), CGRectGetMaxY(self.textView.frame) + 10 + (5 + _imageWidth) * (count / 4), _imageWidth, _imageWidth);
    } completion:^(BOOL finished) {
        
    }];
}


#pragma mark -delegate
-(void)choosePhotoAlbum:(PhotoAlbumModel *)albumModel sender:(UIButton *)sender
{
    [self.assstsArray removeObject:albumModel];
    [self loadAssetsArray:self.assstsArray];
    if (self.editDelegate) {
        [self.editDelegate editDynamicContentWithContent:self.textView.text];
    }
}
#pragma mark - 预览
-(void)preViewPhotoAlbum:(PhotoAlbumModel *)albumModel
{
    [self hiddenKeyBoard];
    
    NSMutableArray * imageArray = [NSMutableArray array];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (PhotoAlbumModel * model in self.assstsArray) {
            if (!model.fullScreenImage) {
                UIImage *image = [UIImage imageWithCGImage:[[model.asset defaultRepresentation] fullScreenImage]];
                model.fullScreenImage = image;
            }
            FullScreenImage * imageModel = [FullScreenImage new];
            imageModel.fullImage = model.fullScreenImage;
            [imageArray addObject:imageModel];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            DealPhotosView * dealPhotosView = [[DealPhotosView alloc] init];
            [dealPhotosView setFullScreenWithImageArray:imageArray showIndex:albumModel.selectedIndex - 1];
            [[[UIApplication sharedApplication].delegate window] addSubview:dealPhotosView];
            
        });
    });
}

#pragma mark - 解决手势响应冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UIScrollView"]) {
        return YES;
    }
    return NO;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hiddenKeyBoard];
}

- (void)textViewDidChange:(YYTextView *)textView
{
    if (textView.text.length > MAX_TEXT_LENGTH) { //内容长度限制为
        textView.text = [textView.text substringToIndex:MAX_TEXT_LENGTH];
    }
    if (self.editDelegate) {
        [self.editDelegate editDynamicContentWithContent:textView.text];
    }
}
#pragma mark - 选择照片、拍照
-(void)editToolBarSeletedIndex:(NSInteger)index
{
    if (self.delegate) {
        [self.delegate editToolBarSeletedIndex:index];
    }
}


#pragma mark - 收回键盘
-(void)hiddenKeyBoard
{
    [self.textView resignFirstResponder];
}
#pragma mark - 显示键盘
-(void)showKeyBoard
{
    [self.textView becomeFirstResponder];
}

#pragma mark - 开始编辑
-(void)startEditing
{
    [self showKeyBoard];
}

#pragma mark - 结束编辑
-(void)endEditing
{
    [self hiddenKeyBoard];
}

@end
